package thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Demo31 {
    public static void main(String[] args) throws InterruptedException {
        //Executors提供了一些工厂方法,可以更方便的构造出线程池
        ExecutorService service = Executors.newFixedThreadPool(4);
        for (int i = 0; i < 100; i++) {
            int id = i;
            service.submit(() -> {
                Thread current = Thread.currentThread();
                //此处的i会报错,原因是"变量捕获"
//                System.out.println("hello thread " + i+ ", " + current.getName());
                System.out.println("hello thread " + id + ", " + current.getName());
            });
        }

        // 最好不要立即就终止, 可能使任务还没执行完呢, 线程就被终止了.
        Thread.sleep(2000);

        // 把线程池里所有的线程都终止掉~~
        service.shutdown();
        System.out.println("程序退出");
    }
}
